/**
 * 列表的滑动行为
 * @param {ref(Array)} list 列表
 */
import { ref, onMounted, getCurrentInstance } from "vue";

export default function behavior(list) {
	const moveItem = ref({
		index: -1,
		pageX: 0,
		width: 0,
	});

	onMounted(() => {
		// 获取页面实例对象
		const instance = getCurrentInstance()
		const query = uni.createSelectorQuery().in(instance)
		query.select('#delete-btn-width').boundingClientRect((data) => {
			moveItem.value.width = data.width;
		}).exec();
	});

	const handleTouchstart = (e, index) => {
		if (moveItem.value.index != index) { // 重置
			list.value.forEach(item => item.moveDistance = 0);
		}
		moveItem.value.index = index;
		moveItem.value.pageX = e.touches[0].pageX;
		list.value[moveItem.value.index].moveDistance = 0;
	}

	const handleTouchmove = (e) => {
		let moveDistance = e.touches[0].pageX - moveItem.value.pageX;
		if (moveDistance > 0) moveDistance = 0;
		else if (moveItem.value.width + moveDistance < 0) moveDistance = -moveItem.value.width;
		list.value[moveItem.value.index].moveDistance = moveDistance;
	}

	const handleTouchend = (e) => {
		if (Math.abs(list.value[moveItem.value.index].moveDistance) > moveItem.value.width / 4) {
			list.value[moveItem.value.index].moveDistance = -moveItem.value.width;
		} else {
			list.value[moveItem.value.index].moveDistance = 0;
		}
	}

	return { handleTouchstart, handleTouchmove, handleTouchend }
}